﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraTreeList;
using DevExpress.XtraTreeList.Nodes;
using QunYing.BLL;
using QunYing.Common;
using Spore.Validator;
using Image = System.Drawing.Image;
using System.ServiceModel;

namespace Client
{
    public partial class FrmCategoryManager : BasePopForm
    {
        private string strPath = string.Empty;
        public FrmCategoryManager()
        {
            InitializeComponent();
            this.NecessaryRemark(this.txtName,txtImage);
            this.FormValidator.SetControlValitors(txtName, ValidatorDefaults.NotNull);
        }

        private void FrmCategoryManager_Load(object sender, EventArgs e)
        {
            QueryData();
        }
        public void QueryData()
        {
            QunYing.BLL.Category category = new Category();
            DataTable dt = category.GetList("经销商编号='"+GlobalInfo.UserLoginInfo.用户ID+"'").Tables[0];
            this.treeList1.DataSource = dt;
            this.treeList1.ParentFieldName = "父类别ID";
            this.treeList1.KeyFieldName = "类别ID";
            this.treeList1.ExpandAll();
        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            OpenFileDialog dag = new OpenFileDialog();
            dag.Filter = "Image Files(*.JPG;*.GIF;*.PNG;*.BMP)|*.JPG;*.GIF;*PNG,*.BMP";
            if (dag.ShowDialog() == DialogResult.OK)
            {
                Image image = Image.FromFile(dag.FileName);
                pictureEdit1.Image = image;
                txtImage.Text = dag.FileName;
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            pictureEdit1.Image = null;
            txtImage.Text = "";
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!this.FormValidator.ValidAll()) return;
            if (txtImage.Text.Trim()=="")
            {
                GlobalInfo.MsgBoxShowError("请选择图标!");
                return;
            }
            int parentID = 0;
            if (cbxTop.Checked)
            {
                parentID = 0;
            }
            else
            {
                if (treeList1.FocusedNode == null)
                {
                    GlobalInfo.MsgBoxShowError("请选择父类别!");
                    return;
                }
                parentID = Convert.ToInt32(treeList1.FocusedNode.GetValue("类别ID"));
            }
            strPath = GetImagePath(parentID);
            QunYing.Model.Category model = new QunYing.Model.Category();
            
            QunYing.BLL.Category category = new Category();
            if (btnSave.Text == "新增(&S)")
            {
                model.父类别ID = parentID;
                model.类别名称 = txtName.Text.Trim();
                model.类别图片 = QunYing.Common.GlobalInfo.ImageRelativePath + strPath;
                model.经销商编号 = GlobalInfo.UserLoginInfo.用户ID;
                model.显示顺序 = 1;

                DataTable dt = category.GetList("类别名称='" + txtName.Text.Trim() + "' and 经销商编号='" + GlobalInfo.UserLoginInfo.用户ID + "'").Tables[0];
                if (dt.Rows.Count>0)
                {
                    GlobalInfo.MsgBoxShowError("类别名称已存在,请更改!");
                    txtName.Focus();
                    return;
                }
                if (category.Add(model) > 0)
                {
                    UploadImg();
                    GlobalInfo.MsgBoxShow("添加成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    QueryData();
                    strPath = string.Empty;

                    InitTxt();
                }
                else
                {
                    GlobalInfo.MsgBoxShowError("添加失败!");
                }
            }
            else if (btnSave.Text == "编辑(&S)")
            {
                model.类别ID = Convert.ToInt32(treeList1.FocusedNode.GetValue("类别ID"));
                model.父类别ID = Convert.ToInt32(treeList1.FocusedNode.GetValue("父类别ID"));
                model.类别名称 = txtName.Text.Trim();
                model.类别图片 = treeList1.FocusedNode.GetValue("类别图片").ToString();
                model.经销商编号 = GlobalInfo.UserLoginInfo.用户ID;
                model.显示顺序 = Convert.ToInt32(treeList1.FocusedNode.GetValue("显示顺序"));

                DataTable dt = category.GetList("类别ID<>'" + treeList1.FocusedNode.GetValue("类别ID") + "' AND 类别名称='" + txtName.Text.Trim() + "'' and 经销商编号='" + GlobalInfo.UserLoginInfo.用户ID + "'").Tables[0];
                if (dt.Rows.Count > 0)
                {
                    GlobalInfo.MsgBoxShowError("类别名称已存在,请更改!");
                    return;
                }

                if (category.Update(model))
                {
                    EditImg(model.类别图片);
                    GlobalInfo.MsgBoxShow("编辑成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    QueryData();
                    strPath = string.Empty;

                    InitTxt();
                }
                else
                {
                    GlobalInfo.MsgBoxShowError("编辑失败!");
                }
            }

        }

        private void InitTxt()
        {
            txtName.Text = string.Empty;
            pictureEdit1.Image = null;
            txtImage.Text = "";
            btnSave.Text = "新增(&S)";
        }

        private bool UploadImg()
        {
            try
            {
                if (string.IsNullOrEmpty(strPath))
                {
                    return false;
                }
                QunYing.Common.IImageOperator opera = QunYing.Common.ClientProxyFactory.GetProxy<QunYing.Common.IImageOperator>(QunYing.Common.GlobalInfo.ServiceImageOperationGoods);
                opera.UpLoad("", new string[] { strPath }, new Bitmap[] { (Bitmap)Bitmap.FromFile(txtImage.Text) });
                (opera as ICommunicationObject).Close();
            }
            catch (Exception ex)
            {
                QunYing.Common.Loger.Log.Error("上传图片时发生错误:" + ex.Message);
            }
            return true;
        }
        private bool EditImg(string path)
        {
            try
            {
                if (txtImage.Text.StartsWith(QunYing.Common.GlobalInfo.ImageRelativePath))
                {
                    return false;
                }
                QunYing.Common.IImageOperator opera = QunYing.Common.ClientProxyFactory.GetProxy<QunYing.Common.IImageOperator>(QunYing.Common.GlobalInfo.ServiceImageOperationGoods);
                opera.UpLoad("", new string[] { path.Substring(9) }, new Bitmap[] { (Bitmap)Bitmap.FromFile(txtImage.Text) });
                (opera as ICommunicationObject).Close();
            }
            catch (Exception ex)
            {
                QunYing.Common.Loger.Log.Error("上传图片时发生错误:" + ex.Message);
            }
            return true;
        }

        private string GetImagePath(int parentID)
        {
            if (string.IsNullOrEmpty(txtImage.Text))
            {
                return "";
            }
            string strType = txtImage.Text.Substring(txtImage.Text.LastIndexOf('.'));
            string strPath = @"Category\" + GlobalInfo.UserLoginInfo.用户ID + @"\" + parentID
                             + (new QunYing.BLL.Category().GetMaxId()) + strType;
            return strPath;
        }

        private void treeList1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                treeList1.ContextMenuStrip = null;
                TreeListHitInfo hInfo = treeList1.CalcHitInfo(new Point(e.X, e.Y));
                TreeListNode node = hInfo.Node;
                treeList1.FocusedNode = node;
                if (node != null)
                {
                    treeList1.ContextMenuStrip = contextMenuStrip1;
                }
            }
        }

        private void 删除节点ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (treeList1.FocusedNode.HasChildren)
            {
                GlobalInfo.MsgBoxShow("请先删除其子类别!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (XtraMessageBox.Show(GlobalInfo.UserLookAndFeel, "确认删除该类别吗？", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
                return;
            string id = treeList1.FocusedNode.GetValue("类别ID").ToString();
            QunYing.BLL.GoodsInfo goods = new GoodsInfo();
            DataSet ds = goods.GetList("类别ID=" + id);
            if (ds.Tables[0].Rows.Count > 0)
            {
                GlobalInfo.MsgBoxShow("该类别下存在商品，不能删除!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            QunYing.BLL.Category category = new Category();
            bool b = category.Delete(Convert.ToInt32(id));
            if (b)
            {
                try
                {
                    QunYing.Common.IImageOperator opera = QunYing.Common.ClientProxyFactory.GetProxy<QunYing.Common.IImageOperator>(QunYing.Common.GlobalInfo.ServiceImageOperationVip);
                    opera.DeleteImg(new string[] { treeList1.FocusedNode.GetValue("类别图片").ToString() });
                    (opera as ICommunicationObject).Close();
                }
                catch (Exception ex)
                {
                    QunYing.Common.Loger.Log.Error("删除图片发生错误:" + ex.Message);
                }
                GlobalInfo.MsgBoxShow("删除成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                QueryData();
            }
            else
            {
                GlobalInfo.MsgBoxShow("删除失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        private void treeList1_DoubleClick(object sender, EventArgs e)
        {
            if (treeList1.FocusedNode != null)
            {
                btnSave.Text = "编辑(&S)";
                txtName.Text = treeList1.FocusedNode.GetValue("类别名称").ToString();
                txtImage.Text = treeList1.FocusedNode.GetValue("类别图片").ToString();

                var opera = ClientProxyFactory.GetProxy<IImageOperator>(QunYing.Common.GlobalInfo.ServiceImageOperationGoods);
                Bitmap[] bp = opera.GetImgs(new string[] { txtImage.Text });
                if (bp.Length != 0)
                {
                    this.pictureEdit1.Image = bp[0];
                }
                (opera as ICommunicationObject).Close();
            }
        }

        private void btnInit_Click(object sender, EventArgs e)
        {
            InitTxt();
        }
    }
}